package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.VideoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class VideoService {
    @Reference
    private VideoApi videoApi;
    @Autowired
    private PicUploadService picUploadService;
    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Autowired
    private UserInfoService userInfoService;
    @Reference
    private QuanZiApi quanZiApi;
    @Autowired
    private QuanZiService quanZiService;
    //发布小视频
    public Boolean saveVideo(MultipartFile picFile, MultipartFile videoFile) {
        User user = UserThreadLocal.get();
        Video video = new Video();
        video.setUserId(user.getId());
        video.setSeeType(1);//公开
        try {
            //上传图片
            PicUploadResult upload = this.picUploadService.upload(picFile);
            video.setPicUrl(upload.getName());
            //上传视频
            StorePath storePath = storageClient.uploadFile(videoFile.getInputStream(),
                    videoFile.getSize(),
                    StrUtil.subAfter(videoFile.getOriginalFilename(), '.', true),
                    null);
            //设置视频路径
            video.setVideoUrl(fdfsWebServer.getWebServerUrl()+storePath.getFullPath());
            //保存
            String videoId = videoApi.saveVideo(video);
            return StrUtil.isNotEmpty(videoId);
        } catch (IOException e) {
            log.error("发布小视频失败！file = " + picFile.getOriginalFilename() , e);
        }
        return false;
    }
    //查询视频列表
    public PageResult queryVideoList(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        PageInfo<Video> pageInfo = this.videoApi.queryVideoList(user.getId(), page, pageSize);
        List<Video> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)){
            return pageResult;
        }
        //查询用户信息
        List<Object> userIds= CollUtil.getFieldValues(records, "userId");
        //获取UserInfo集合
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(userIds);
        List<VideoVo> videoVoList = new ArrayList<>();
        for (Video record : records) {
            VideoVo videoVo = new VideoVo();

            videoVo.setUserId(record.getUserId());
            videoVo.setCover(record.getPicUrl());
            videoVo.setVideoUrl(record.getVideoUrl());
            videoVo.setId(record.getId().toHexString());
            videoVo.setSignature("我就是我~"); //TODO 签名

            videoVo.setCommentCount(Convert.toInt(this.quanZiApi.queryCommentCount(videoVo.getId()))); //评论数
            videoVo.setHasFocus(0); //TODO 是否关注
            videoVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), videoVo.getId()) ? 1 : 0); //是否点赞（1是，0否）
            videoVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(videoVo.getId())));//点赞数

            //填充用户信息
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(videoVo.getUserId(), userInfo.getUserId())) {
                    videoVo.setNickname(userInfo.getNickName());
                    videoVo.setAvatar(userInfo.getLogo());
                    break;
                }
            }
            videoVoList.add(videoVo);
        }
        pageResult.setItems(videoVoList);
        return pageResult;
    }
    //点赞
    public Long likeComment(String videoId) {
        User user = UserThreadLocal.get();
        Boolean result = this.quanZiApi.likeComment(user.getId(), videoId);
        if (result){
            System.out.println("点赞成功");
            return this.quanZiApi.queryLikeCount(videoId);
        }
        return null;
    }
    /**
     * 取消点赞
     *
     * @param videoId
     * @return
     */
    public Long disLikeComment(String videoId) {
        User user = UserThreadLocal.get();
        Boolean result = this.quanZiApi.disLikeComment(user.getId(), videoId);
        if (result) {
            System.out.println("取消成功");
            return this.quanZiApi.queryLikeCount(videoId);
        }
        return null;
    }
    //查询小视频评论列表
    public PageResult queryCommentList(String videoId, Integer page, Integer pageSize) {
       return this.quanZiService.queryCommentList(videoId,page,pageSize);
    }
    //保存评论
    public Boolean saveComment(String videoId, String content) {
        return this.quanZiService.saveComments(videoId,content);
    }

}
